import 'package:basic_library/basic_library.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'dart:math' as math;

///
/// 载入 APP 启动页/广告
///
class SplashFrame extends StatefulWidget {
  final Widget child;
  final Function downCallback;
  const SplashFrame({Key? key, required this.child, required this.downCallback}) : super(key: key);

  @override
  _SplashFrameState createState() => _SplashFrameState();
}

class _SplashFrameState extends State<SplashFrame> with HQBase {
  late SharedPreferences prefs;

  @override
  void initState() {
    super.initState();
    _initAsync();
    _getNav();
    _getSwiperPic();
    _initLiveData();
  }

  void _initAsync() async {
    // App启动时读取Sp数据，需要异步等待Sp初始化完成。
    prefs = await SharedPreferences.getInstance();
  }

  // 获取导航列表
  void _getNav() {
    // final indexBloc = BlocProvider.of<IndexBloc>(context);
    //
    // httpClient.get(
    //   API.nav,
    // ).then((res) {
    //   var navList = res.data['data'];
    //   indexBloc.add(UpdateTab(navList));
    // });
  }

  // 获取轮播图列表
  void _getSwiperPic() {
    // final indexBloc = BlocProvider.of<IndexBloc>(context);
    //
    // httpClient.post(
    //   API.swiper,
    //   data: FormData.fromMap({
    //     'num': 4
    //   }),
    //   options: buildCacheOptions(
    //     Duration(minutes: 30),
    //     // options: Options(contentType: ContentType.parse("application/x-www-form-urlencoded"))
    //   ),
    // ).then((res) {
    //   var swiper = res.data['data'];
    //   indexBloc.add(UpdateSwiper(swiper));
    // }).catchError((err) {
    //   indexBloc.add(UpdateSwiper(null));
    // });
  }

  void _initLiveData() async {
    // final indexBloc = BlocProvider.of<IndexBloc>(context);
    //
    // var liveList = await DYservice.getLiveData(context);
    // indexBloc.add(UpdateLiveData(liveList));
  }

  @override
  Widget build(BuildContext context) {
    // ScreenUtil.instance = ScreenUtil(width: DYBase.dessignWidth)..init(context);
    return Scaffold(
      body: SizedBox(
        width: MediaQuery.of(context).size.width,
        child: Stack(
          children: <Widget>[
            widget.child,
            Positioned(
              right: 25,
              top: 35,
              child: CountdownInit(downCallback: widget.downCallback),
            ),
          ],
        ),
      ),
    );
  }
}


///
/// 启动页右上角倒计时
///
class CountdownInit extends StatefulWidget {
  final Function downCallback;
  const CountdownInit({Key? key, required this.downCallback}) : super(key: key);

  @override
  _CountdownInit createState() => _CountdownInit();
}

class _CountdownInit extends State<CountdownInit> with HQBase, SingleTickerProviderStateMixin {
  late Animation<double> _animation;         // canvas转动动画函数
  late AnimationController _controller;      // canvas转动动画控制器
  final int _time = 5;                        // 首页载入秒数

  @override
  void initState() {
    super.initState();
    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
      statusBarBrightness: Brightness.light,
      statusBarIconBrightness: Brightness.light,
    ));
    // SystemChrome.setEnabledSystemUIOverlays([]);

    _controller = AnimationController(duration: Duration(seconds: _time), vsync: this,);  // 倒计时动画控制器
    _animation = Tween(begin: 0.0, end: 360.0).animate(_controller);
    _controller.addListener(() {
      setState(() {});
    });
    _controller.addStatusListener((AnimationStatus a) {
      if (a == AnimationStatus.completed) {
        _jumpIndex();
      }
    });
    _controller.forward();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  void _jumpIndex() {
    widget.downCallback.call();
    // Navigator.of(context).pushReplacementNamed('/index');
    /* Future.delayed(Duration(milliseconds: 300), () {
      SystemChrome.setEnabledSystemUIOverlays(SystemUiOverlay.values);
    }); */
  }

  @override
  Widget build(BuildContext context) {
    // ScreenUtil.instance = ScreenUtil(width: DYBase.dessignWidth)..init(context);
    var countNum = _time - (_animation.value * _time / 360).round();

    return GestureDetector(
      onTap: _jumpIndex,
      child: Container(
        width: 25,
        height: 25,
        decoration: const ShapeDecoration(
          color: Color.fromARGB(70, 0, 0, 0),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.all(
              Radius.circular(25),
            ),
          ),
        ),
        child: CustomPaint(
          child: Center(
            child: Text(
              '${countNum}s',
              style: const TextStyle(
                color: Colors.white,
                fontSize: 16,
              ),
            ),
          ),
          painter: CircleProgressBarPainter(_animation.value),
        ),
      ),
    );
  }

}

// 画布绘制加载倒计时
class CircleProgressBarPainter extends CustomPainter {
  // Paint _paintBackground;
  late Paint _paintFore;
  final rate;

  CircleProgressBarPainter(this.rate) {
    // _paintBackground = Paint()
    //   ..color = Colors.white
    //   ..strokeCap = StrokeCap.round
    //   ..style = PaintingStyle.stroke
    //   ..strokeWidth = 2.0
    //   ..isAntiAlias = true;
    _paintFore = Paint()
      ..color = Colors.white
      ..strokeCap = StrokeCap.round
      ..style = PaintingStyle.stroke
      ..strokeWidth = 10.0
      ..isAntiAlias = true;
  }
  @override
  void paint(Canvas canvas, Size size) {
    /* canvas.drawCircle(Offset(size.width / 2, size.height / 2), size.width / 2,
        _paintBackground); */
    Rect rect = Rect.fromCircle(
      center: Offset(size.width / 2, size.height / 2),
      radius: size.width / 2,
    );
    canvas.drawArc(rect, 0.0, rate * math.pi / 180, false, _paintFore);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return true;
  }
}
